"""
   matplotlib入门
"""
import matplotlib.pyplot as plt
import numpy as np
from numpy.random import randn
import pandas as pd
from datetime import datetime


def test_01():
    plt.plot(np.arange(10))
    plt.show()


def test_02():
    fig = plt.figure()
    # 图像应该是2*2的，且当前选中的是4个subplot中的第一个（编号从1开始）
    ax1 = fig.add_subplot(2, 2, 1)
    ax2 = fig.add_subplot(2, 2, 2)
    ax3 = fig.add_subplot(2, 2, 3)
    plt.plot(randn(50).cumsum(), 'k--')
    ax1.hist(randn(100), bins=20, color='k', alpha=0.3)
    ax2.scatter(np.arange(30), np.arange(30) + 3 * randn(30))
    plt.show()


def test_03():
    fig, axes = plt.subplots(2, 3)
    print(axes)
    print(axes[0, 1])


def test_04():
    """
    调整subplot周围的间距
    :return:
    """
    fig, axes = plt.subplots(2, 2, sharex=True, sharey=True)
    for i in range(2):
        for j in range(2):
            axes[i, j].hist(randn(500), bins=50, color='k', alpha=0.5)
    plt.subplots_adjust(wspace=0, hspace=0)
    plt.show()
    # 结果和书上不一致


def test_05():
    """
    颜色、标记和线型
    :return:
    """
    # plt.plot(randn(30).cumsum(), 'ko--')
    # plt.plot(randn(30).cumsum(), color='k', linestyle='dashed', marker='o')
    data = randn(30).cumsum()
    # plt.plot(data, 'k--', label='Default')
    plt.plot(data, 'k--', drawstyle='steps-post', label='steps-post')
    plt.legend(loc='best')
    plt.show()


def test_06():
    """
    刻度、标签和图例
    :return:
    """
    # xlim、xticks、xticklabels分别控制图标的范围、刻度位置、刻度标签

    # # 设置标题、轴标签、刻度以及刻度标签
    # fig = plt.figure()
    # ax = fig.add_subplot(1, 1, 1)
    # ax.plot(randn(1000).cumsum())
    # # 修改x轴的刻度
    # ax.set_xticks([0, 250, 500, 750, 1000])
    # ax.set_xticklabels(['one', 'two', 'three', 'four', 'five'], rotation=30, fontsize='small')
    # ax.set_title('My first matplotlib plot')
    # ax.set_xlabel('Stages')
    # plt.show()

    # 添加图例
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)
    ax.plot(randn(1000).cumsum(), 'k', label='one')
    ax.plot(randn(1000).cumsum(), 'k--', color='g', label='two')
    ax.plot(randn(1000).cumsum(), 'k.', color='r', label='three')
    ax.legend(loc='best')
    plt.show()


def test_07():
    """
    注解以及在Subplot上绘图
    :return:
    """
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)

    data = pd.read_csv('spx.csv', index_col=0, parse_dates=True)
    spx = data['SPX']

    spx.plot(ax=ax, style='k-')

    crisis_data = [
        (datetime(2007, 10, 11), 'Peak of bull market'),
        (datetime(2008, 3, 12), 'Bear Stearns Fails'),
        (datetime(2008, 9, 15), 'Lehman Bankruptcy')
    ]

    for date, label in crisis_data:
        ax.annotate(label, xy=(date, spx.asof(date) + 50),
                    xytext=(date, spx.asof(date) + 200),
                    arrowprops=dict(facecolor='black'),
                    horizontalalignment='left', verticalalignment='top')

    # 放大到2007-2010
    ax.set_xlim(['1/1/2007', '1/1/2011'])
    ax.set_ylim([600, 1800])

    ax.set_title('Important dates in 2008-2009 financial crisis')

    plt.show()


def test_08():
    """
    在图标中添加图形
    :return:
    """
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)

    rect = plt.Rectangle((0.2, 0.75), 0.4, 0.15, color='k', alpha=0.3)
    circ = plt.Circle((0.7, 0.2), 0.15, color='b', alpha=0.3)
    pgon = plt.Polygon([[0.15, 0.15], [0.35, 0.4], [0.2, 0.6]], color='k', alpha=0.5)

    ax.add_patch(rect)
    ax.add_patch(circ)
    ax.add_patch(pgon)

    plt.show()


def test_09():
    """
    将图标保存到文件
    :return:
    """
    plt.savefig('figpath.png', dpi=400, bbox_inches='tight')


def main():
    # test_01()
    # test_02()
    # test_03()
    # test_04()
    # test_05()
    # test_06()
    # test_07()
    # test_08()
    test_09()


if __name__ == '__main__':
    main()
